package com.zwh.chatgpt.test.domain.zsxq.service;

import com.alibaba.fastjson.JSON;
import com.zwh.chatgpt.test.domain.zsxq.IZsxqAi;
import com.zwh.chatgpt.test.domain.zsxq.model.aggregates.UnAnsweredQuestionsAggregates;
import com.zwh.chatgpt.test.domain.zsxq.model.req.AnswerReq;
import com.zwh.chatgpt.test.domain.zsxq.model.req.ReqData;
import net.sf.json.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ZsxqAi implements IZsxqAi {

    @Override
    public UnAnsweredQuestionsAggregates queryUnAnsweredQuestionsTopicId(String groupId, String cookie) throws IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();//用来封装一些数据信息

        HttpGet get = new HttpGet("https://api.zsxq.com/v2/groups/"+groupId+"/topics?scope=all&count=20");//用HttpGet来获取地址

        get.addHeader("cookie",cookie);
        get.addHeader("Content-Type","application/json; charset=UTF-8");

        CloseableHttpResponse response = httpClient.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            String jsonStr = EntityUtils.toString(response.getEntity());
            return JSON.parseObject(jsonStr,UnAnsweredQuestionsAggregates.class);
        }else{
            throw new RuntimeException("异常：" + response.getStatusLine().getStatusCode());
        }

    }

    @Override
    public boolean answer(String groupId, String cookie, String topicId, String text, boolean silenced) throws IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost("https://api.zsxq.com/v2/topics/"+topicId+"/comments");//这是评论comments的URL
        post.addHeader("cookie",cookie);
        post.addHeader("Content-Type","application/json;charset=UTF-8");

        AnswerReq answerReq = new AnswerReq(new ReqData(text,silenced));
        String paramjason = JSONObject.fromObject(answerReq).toString();

        StringEntity stringEntity = new StringEntity(paramjason, ContentType.create("text/json","UTF-8"));
        post.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(post);//把这个post信息执行了

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

            String res = EntityUtils.toString(response.getEntity());
            System.out.println(res);

        }else{
            System.out.println(response.getStatusLine().getStatusCode());
        }

        return silenced;
    }
}
